package red.mlz.app.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import red.mlz.app.domain.homepage.*;
import red.mlz.module.module.category.entity.Category;
import red.mlz.module.module.category.service.CategoryService;
import red.mlz.module.module.game.entity.Game;
import red.mlz.module.module.game.service.GameService;
import red.mlz.module.utils.ImageUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
public class HomePageService {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private GameService gameService;

    private static final int THREAD_POOL_SIZE = 5;
    private final ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);

    public HomePageVo getHomePageData() {
        HomePageVo homePageVo = new HomePageVo();

        //异步获取各模块数据
        CompletableFuture<List<CategoryVo>> categoryFuture = CompletableFuture.supplyAsync(this::getCategoryData, executor);
        CompletableFuture<List<BannerVo>> bannerFuture = CompletableFuture.supplyAsync(this::getBannerData, executor);
        CompletableFuture<List<ChannelVo>> channelFuture = CompletableFuture.supplyAsync(this::getChannelData, executor);
        CompletableFuture<List<ActivityVo>> activityFuture = CompletableFuture.supplyAsync(this::getActivityData, executor);
        CompletableFuture<List<RecommendVo>> recommendFuture = CompletableFuture.supplyAsync(this::getRecommendData, executor);

        // 等待所有任务完成
        CompletableFuture.allOf(bannerFuture, categoryFuture, channelFuture, activityFuture, recommendFuture).join();

        try {
            homePageVo.setBannerList(bannerFuture.get());
            homePageVo.setCategoryList(categoryFuture.get());
            homePageVo.setChannelList(channelFuture.get());
            homePageVo.setActivityList(activityFuture.get());
            homePageVo.setRecommendList(recommendFuture.get());
        } catch (Exception e) {
            log.error("获取首页数据失败", e);
        }

        return homePageVo;

    }

    private List<CategoryVo> getCategoryData() {
        Long parentId = 0L;
        List<String> categoryList =  categoryService.getCategoryNameByParentId(parentId);
        List<CategoryVo> categoryVoList = new ArrayList<>();
        for (String categoryName : categoryList) {
            CategoryVo categoryVo = new CategoryVo();
            categoryVo.setCategoryName(categoryName);
            categoryVoList.add(categoryVo);
        }
        return categoryVoList;
    }

    private List<BannerVo> getBannerData() {
        // 模拟数据
        List<BannerVo> bannerList = new ArrayList<>();
        BannerVo banner1 = new BannerVo();
        banner1.setImageUrl("https://example.com/banner1.jpg");
        banner1.setLink("https://example.com/link1");
        bannerList.add(banner1);
        return bannerList;
    }

    private List<ChannelVo> getChannelData() {
        // 模拟数据
        List<ChannelVo> channelList = new ArrayList<>();
        ChannelVo channel1 = new ChannelVo();
        channel1.setImageUrl("https://example.com/channel1.jpg");
        channel1.setTitle("Channel 1");
        channel1.setChannelId(1L);
        channelList.add(channel1);
        return channelList;
    }

    private List<ActivityVo> getActivityData() {
        // 模拟数据
        List<ActivityVo> activityList = new ArrayList<>();
        ActivityVo activity1 = new ActivityVo();
        activity1.setImageUrl("https://example.com/activity1.jpg");
        activity1.setTitle("Activity 1");
        activity1.setActivityId(1L);
        activityList.add(activity1);
        return activityList;
    }

    private List<RecommendVo> getRecommendData() {
        List<Game> games = gameService.getAllGames(1, 5, null);
        // 收集所有categoryId
        List<Long> categoryIds = games.stream()
                .map(Game::getCategoryId)
                .distinct()
                .collect(Collectors.toList());

        // 批量查询分类信息
        List<Category> categories = categoryService.listByIds(categoryIds);
        Map<Long, Category> categoryMap = categories.stream()
                .collect(Collectors.toMap(Category::getId, Function.identity()));

        List<RecommendVo> gameItems = games.stream()
                .map(game -> {
                    RecommendVo itemVO = new RecommendVo();
                    itemVO.setId(game.getId());
                    // 处理图片信息
                    RecommendVo.ImageInfo imageInfo = new RecommendVo.ImageInfo();
                    String imageUrl = game.getCoverImages();

                    // 处理图片URL
                    if (imageUrl != null && !imageUrl.isEmpty()) {
                        // 设置原图URL（去掉参数保留基础地址）
                        imageInfo.setUrl(imageUrl.split("\\?")[0]);
                        // 从文件名提取宽高比
                        Float aspectRatio = ImageUtils.parseAspectRatio(imageUrl);
                        imageInfo.setAr(String.valueOf(aspectRatio));
                    } else {
                        // 设置默认图片URL和宽高比
                        imageInfo.setUrl("");
                        imageInfo.setAr("1.0");
                    }

                    itemVO.setImage(imageInfo);
                    itemVO.setGameName(game.getGameName());
                    itemVO.setPlayerNumber(game.getPlayerNumber());
                    Long categoryId = game.getCategoryId();
                    Category category = categoryMap.get(categoryId);
                    if (category != null) {
                        itemVO.setCategoryName(category.getName());
                    } else {
                        // 处理分类不存在的情况
                        itemVO.setCategoryName("未知分类");
                    }
                    return itemVO;
                })
                .collect(Collectors.toList());

        return gameItems;
    }
}

